using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SmartLink.Domain.Entity;
using SmartLink.IRepository;
using SmartLink.Repository.Base;
using Dapper;

namespace SmartLink.Repository
{
    public class SYS_MenuRepo : RepositoryBase<SYS_Menu>, ISYS_MenuRepo
    {
        public void AddMenu(SYS_Menu menu)
        {
            Add(menu);
        }

        public bool Update(SYS_Menu menu)
        {
            return base.Update(menu);
        }

        public bool Delete(int menuId)
        {
            SYS_Menu curMenu = GetById(menuId);
            string parentIDIndexLike = curMenu.ParentIDIndex + "_" + curMenu.ID;
            return DeleteAllChildMenus(menuId, parentIDIndexLike);
        }

        public bool CheckExistByMenuName(string menuName)
        {
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format($@"SELECT count(*) from  where menuName='{menuName}'");
                int count = Convert.ToInt32(conn.ExecuteScalar(sql).ToString());
                conn.Close();
                return count > 0 ? true : false;
            }
        }


        /// <summary>
        /// 根据菜单id获取具体菜单
        /// </summary>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        public IList<SYS_Menu> GetMenusByIds(IList<int> menuIds)
        {
            IList<SYS_Menu> menus = new List<SYS_Menu>();
            string whereStr = "";
            if (menuIds.Count > 0)
                whereStr = "where id in (" + string.Join(",", menuIds) + ")";
            else
                return menus;
            var sql = string.Format(" select *  from SYS_Menu  {0} order by sort", whereStr);
            menus = GetBySql(sql).ToList();
            return menus;
        }

        public IList<SYS_Menu> GetAllMenus()
        {
            IList<SYS_Menu> menus = new List<SYS_Menu>();
            var sql = " select *  from SYS_Menu  order by sort";
            menus = GetBySql(sql).ToList();
            return menus;
        }

        /// <summary>
        /// 获取改pid下的最大的sort排序
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public SYS_Menu GetMaxSortMenuByParentId(int pid)
        {
            SYS_Menu menu;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                string whereStr = "where ParentID =" + pid;
                var sql = string.Format(" select  * from SYS_Menu {0} order by sort desc limit 1", whereStr);
                SYS_Menu men = conn.QueryFirstOrDefault<SYS_Menu>(sql);
                menu = men;
                conn.Close();
            }
            return menu;
        }

        public IList<int> GetRoleMenuIds(int RoleId)
        {
            IList<int> userMenuIds = new List<int>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(@"select mpr.MenuID from PER_MenuPermissionsRole mpr 
                                               where mpr.RID =@RID");
                userMenuIds = conn.Query<int>(sql, new { RID = RoleId }).ToList();
                conn.Close();
                return userMenuIds;
            }
        }

        /// <summary>
        /// 获取用户的角色下的菜单id集合
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public IList<int> GetUserMenuIds(int userId)
        {
            IList<int> userMenuIds = new List<int>();
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = string.Format(@"select mpr.MenuID from PER_UserToRole utr inner join PER_MenuPermissionsRole mpr 
                                               on utr.RID = mpr.RID
                                               where utr.UserID =@UserId ");
                userMenuIds = conn.Query<int>(sql, new { UserId = userId }).ToList();
                conn.Close();

                return userMenuIds;
            }
        }

        /// <summary>
        /// 删除节点的同时，删除所有的孩子结点
        /// </summary>
        /// <param name="pId"></param>
        /// <param name="parentIDIndexLike"></param>
        /// <returns></returns>
        private bool DeleteAllChildMenus(int pId, string parentIDIndexLike)
        {
            bool result = false;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                string whereStr = string.Format(" where ParentIDIndex like '%{0}%' or id ={1}", parentIDIndexLike, pId);
                var sql = string.Format(" delete  from SYS_Menu {0} ", whereStr);
                int count = conn.Execute(sql);
                if (count > 0)
                    result = true;
                conn.Close();
            }
            return result;
        }

        public bool CheckExistSameLevelMenuByMenuName(int pId, string menuName)
        {
            //-1下的菜单特殊处理
            bool result = false;
            SYS_Menu curMenu = null;
            string parentIDIndexLike = "";
            if (pId == -1)
                parentIDIndexLike = "-1";
            else
                curMenu = GetById(pId);

            if (curMenu != null)
                parentIDIndexLike = curMenu.ParentIDIndex + "_" + curMenu.ID;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                string sql = string.Format(@" select count(*) from  SYS_Menu
                                                where ParentIDIndex like '%{0}%' and menuName='{1}'", parentIDIndexLike, menuName);
                int count = Convert.ToInt32(conn.ExecuteScalar(sql));
                if (count > 0)
                    result = true;
                conn.Close();
            }
            return result;
        }

        public bool CheckExistSameLevelMenuByMenuNameForUpdate(int pId, string menuName)
        {
            bool result = true;
            SYS_Menu curMenu = GetById(pId);
            string parentIDIndexLike = curMenu.ParentIDIndex + "_" + curMenu.ID;
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                string sql = string.Format(@" select count(*) from  SYS_Menu
                                                where ParentIDIndex = '%{0}%' and menuName='{1}'", parentIDIndexLike, menuName);
                int count = conn.Execute(sql);
                if (count > 1)
                    result = true;
                conn.Close();
            }
            result = false;
            return result;
        }


    }
}
